package com.friend.controller.question.file;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.file.config.OSSProperties;
import com.friend.domain.user.User;
import com.friend.mapper.user.UserMapper;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * 图片代理控制器
 * 通过后端代理访问 OSS 图片，隐藏 OSS 配置信息
 */
@Slf4j
@RestController
@RequestMapping("/image")
public class ImageProxyController {

    @Autowired
    private OSS ossClient;

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取用户头像（通过用户ID）
     * @param userId 用户ID
     * @return 头像图片二进制数据
     */
    @GetMapping("/avatar/{userId}")
    public ResponseEntity<byte[]> getUserAvatar(@PathVariable Long userId) {
        try {
            // 从数据库获取用户头像 key
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .select(User::getHeadImage)
                    .eq(User::getUserId, userId));
            
            if (user == null || StrUtil.isBlank(user.getHeadImage())) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            
            String headImageValue = user.getHeadImage();
            
            // 提取真正的 OSS key（兼容旧数据）
            String headImageKey = extractKeyFromValue(headImageValue);
            
            return getImageByKey(headImageKey);
            
        } catch (Exception e) {
            log.error("获取用户头像失败: {}", e.getMessage(), e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 从数据库中的值提取真正的 OSS key
     * 兼容多种格式：
     * 1. ojsystem/xxx.jpg (直接是key)
     * 2. /dev-api/image/proxy?key=ojsystem/xxx.jpg (代理URL)
     * 3. https://bucket.oss-cn-hangzhou.aliyuncs.com/ojsystem/xxx.jpg (完整OSS URL)
     */
    private String extractKeyFromValue(String value) {
        if (StrUtil.isBlank(value)) {
            return value;
        }
        
        // 如果包含 "key=" 说明是代理URL格式
        if (value.contains("key=")) {
            int keyIndex = value.indexOf("key=");
            return value.substring(keyIndex + 4);
        }
        
        // 如果是 HTTP/HTTPS URL，提取路径部分
        if (value.startsWith("http://") || value.startsWith("https://")) {
            try {
                // 找到第一个 '/' 后的内容
                String withoutProtocol = value.substring(value.indexOf("://") + 3);
                int firstSlash = withoutProtocol.indexOf('/');
                if (firstSlash != -1) {
                    return withoutProtocol.substring(firstSlash + 1);
                }
            } catch (Exception e) {
                log.warn("解析 HTTP URL 失败: {}", value);
            }
        }
        
        // 否则认为直接是 key
        return value;
    }

    /**
     * 代理获取图片
     * @param key 图片在 OSS 中的 key，例如: ojtest/xxx.jpg
     * @return 图片二进制数据
     */
    @GetMapping("/proxy")
    public ResponseEntity<byte[]> proxyImage(@RequestParam String key) {
        try {
            log.info("代理请求图片，key: {}", key);
            return getImageByKey(key);
        } catch (Exception e) {
            log.error("代理图片失败，key: {}, error: {}", key, e.getMessage());
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 根据 key 从 OSS 获取图片
     * @param key 图片 key
     * @return 图片二进制数据
     */
    private ResponseEntity<byte[]> getImageByKey(String key) {
        try {
            // 从 OSS 获取文件
            OSSObject ossObject = ossClient.getObject(ossProperties.getBucketName(), key);
            
            // 读取文件流
            InputStream inputStream = ossObject.getObjectContent();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = outputStream.toByteArray();
            
            // 关闭流
            inputStream.close();
            outputStream.close();
            ossObject.close();
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            
            // 根据文件扩展名设置 Content-Type
            String contentType = getContentType(key);
            headers.setContentType(MediaType.parseMediaType(contentType));
            
            // 设置缓存（1天）
            headers.setCacheControl("public, max-age=86400");
            
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
            
        } catch (Exception e) {
            log.error("获取图片失败，key: {}, error: {}", key, e.getMessage());
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    
    /**
     * 根据文件扩展名获取 Content-Type
     */
    private String getContentType(String key) {
        String lowerKey = key.toLowerCase();
        if (lowerKey.endsWith(".jpg") || lowerKey.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (lowerKey.endsWith(".png")) {
            return "image/png";
        } else if (lowerKey.endsWith(".gif")) {
            return "image/gif";
        } else if (lowerKey.endsWith(".webp")) {
            return "image/webp";
        } else if (lowerKey.endsWith(".svg")) {
            return "image/svg+xml";
        }
        return "image/jpeg"; // 默认
    }
}

